<template>
  <div class="pdf-container">
    <!-- PDF 控制栏 -->
    <div class="pdf-controls">
      <el-button-group>
        <el-button :icon="ArrowLeft" @click="prevPage" :disabled="currentPage <= 1" size="small">
          上一页
        </el-button>
        <el-button @click="nextPage" :disabled="currentPage >= totalPages" size="small">
          下一页
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </el-button-group>

      <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>

      <el-button-group>
        <el-button :icon="ZoomOut" @click="zoomOut" :disabled="scale <= 0.6" size="small">
          缩小
        </el-button>
        <el-button :icon="ZoomIn" @click="zoomIn" :disabled="scale >= 3" size="small">
          放大
        </el-button>
      </el-button-group>

      <span class="zoom-info">{{ Math.round(scale * 100) }}%</span>

      <el-button :icon="Refresh" @click="resetPdf" size="small">
        重置
      </el-button>
    </div>

    <!-- PDF 显示区域 -->
    <div class="pdf-viewer" ref="pdfViewer">
      <div v-if="loading" class="pdf-loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载PDF...</span>
      </div>

      <div v-else-if="error" class="pdf-error">
        <el-icon><CircleClose /></el-icon>
        <span>加载PDF失败: {{ error }}</span>
        <el-button @click="loadPdf" type="primary">重试</el-button>
      </div>

      <canvas v-else ref="pdfCanvas"></canvas>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as pdfjsLib from 'pdfjs-dist'
import {
  ArrowLeft,
  ArrowRight,
  ZoomIn,
  ZoomOut,
  Refresh,
  Loading,
  CircleClose
} from '@element-plus/icons-vue'

// 设置 PDF.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`

const props = defineProps({
  pdfUrl: {
    type: String,
    required: true
  },
  height: {
    type: Number,
    default: 600
  }
})

const emit = defineEmits(['load-complete', 'load-error'])

const pdfCanvas = ref(null)
const pdfViewer = ref(null)
const currentPage = ref(1)
const totalPages = ref(0)
const scale = ref(1.2)
const pdfDoc = ref(null)
const loading = ref(false)
const error = ref('')

// 渲染 PDF 页面
const renderPage = async (pageNum) => {
  if (!pdfDoc.value) return

  try {
    const page = await pdfDoc.value.getPage(pageNum)
    const canvas = pdfCanvas.value
    const ctx = canvas.getContext('2d')

    const viewport = page.getViewport({ scale: scale.value })

    canvas.height = viewport.height
    canvas.width = viewport.width

    // 设置 canvas 显示大小
    canvas.style.height = 'auto'
    canvas.style.width = 'auto'
    canvas.style.maxWidth = '100%'

    const renderContext = {
      canvasContext: ctx,
      viewport: viewport
    }

    await page.render(renderContext).promise
  } catch (err) {
    console.error('渲染PDF页面失败:', err)
    error.value = '渲染PDF页面失败'
  }
}

// 加载 PDF
const loadPdf = async () => {
  if (!props.pdfUrl) return

  loading.value = true
  error.value = ''

  try {
    // 清理之前的 PDF 文档
    if (pdfDoc.value) {
      pdfDoc.value.destroy()
      pdfDoc.value = null
    }

    const loadingTask = pdfjsLib.getDocument(props.pdfUrl)
    pdfDoc.value = await loadingTask.promise
    totalPages.value = pdfDoc.value.numPages
    currentPage.value = 1

    await nextTick()
    await renderPage(1)

    emit('load-complete', {
      totalPages: totalPages.value,
      pdfDoc: pdfDoc.value
    })
  } catch (err) {
    console.error('加载PDF失败:', err)
    error.value = err.message || '加载PDF文件失败'
    emit('load-error', error.value)
  } finally {
    loading.value = false
  }
}

// 上一页
const prevPage = async () => {
  if (currentPage.value > 1) {
    currentPage.value--
    await renderPage(currentPage.value)
  }
}

// 下一页
const nextPage = async () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    await renderPage(currentPage.value)
  }
}

// 放大
const zoomIn = async () => {
  if (scale.value < 3) {
    scale.value += 0.2
    await renderPage(currentPage.value)
  }
}

// 缩小
const zoomOut = async () => {
  if (scale.value > 0.6) {
    scale.value -= 0.2
    await renderPage(currentPage.value)
  }
}

// 重置 PDF
const resetPdf = async () => {
  scale.value = 1.2
  currentPage.value = 1
  if (pdfDoc.value) {
    await renderPage(1)
  }
}

// 跳转到指定页面
const gotoPage = async (pageNum) => {
  if (pageNum >= 1 && pageNum <= totalPages.value) {
    currentPage.value = pageNum
    await renderPage(pageNum)
  }
}

// 监听 PDF URL 变化
watch(() => props.pdfUrl, (newUrl) => {
  if (newUrl) {
    loadPdf()
  }
})

onMounted(() => {
  if (props.pdfUrl) {
    loadPdf()
  }
})

onUnmounted(() => {
  if (pdfDoc.value) {
    pdfDoc.value.destroy()
  }
})

// 暴露方法给父组件
defineExpose({
  prevPage,
  nextPage,
  gotoPage,
  zoomIn,
  zoomOut,
  resetPdf,
  currentPage,
  totalPages,
  scale
})
</script>

<style scoped lang="scss">
.pdf-container {
  border: 1px solid #e9ecef;
  border-radius: 4px;
  background: white;
}

.pdf-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  flex-wrap: wrap;

  .page-info, .zoom-info {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
  }
}

.pdf-viewer {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 200px;
  padding: 20px;
  overflow: auto;

  canvas {
    border: 1px solid #ddd;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
}

.pdf-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #606266;

  .el-icon {
    font-size: 24px;
    color: #409eff;
  }
}

.pdf-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: #f56c6c;
  padding: 20px;

  .el-icon {
    font-size: 32px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .pdf-controls {
    flex-direction: column;
    gap: 8px;

    .el-button-group {
      display: flex;
      justify-content: center;
    }
  }

  .pdf-viewer {
    padding: 10px;

    canvas {
      max-width: 100%;
    }
  }
}
</style>